package com.tanhua.dubbo.api;

import com.tanhua.dubbo.api.mongo.VideoApi;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

/**
 * 小视频服务接口实现类
 */
@DubboService
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    /**
     * 视频发布
     * @param video
     */
    @Override
    public void add(Video video) {
        video.setVid(idWorker.getNextId("video"));//推荐系统有关主键id
        video.setCreated(System.currentTimeMillis());//视频发布时间
        mongoTemplate.insert(video);
    }

    /**
     * 根据vids查询视频表
     * @param listVids
     * @return
     */
    @Override
    public List<Video> findByVids(List<Long> listVids) {
        Query query = new Query();
        query.addCriteria(Criteria.where("vid").in(listVids));
        return mongoTemplate.find(query,Video.class);
    }
    /**
     * 根据分页参数按照时间倒序查询视频表
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult<Video> findPage(long page, Long pageSize) {
        //定义返回PageResult<Video>
        PageResult<Video> pageResult = new PageResult<>();
        Query query = new Query();
        //1查询总记录数
        long counts = mongoTemplate.count(query, Video.class);
        long start = (page - 1) * pageSize;
        //2查询当前页面需要展示的数据
        List<Video> videoList = new ArrayList<>();
        if (counts > start) { //20 > 27
            //构造分页limit 0,3
            query.limit(pageSize.intValue());//每页查询几条
            query.skip(start);//跳过1条数据
            //query.with(PageRequest.of(page-1,pageSize));
            query.with(Sort.by(Sort.Direction.DESC, "created"));
            videoList = mongoTemplate.find(query, Video.class);
        }
        return new PageResult<>(page, pageSize, counts, videoList);
    }
}
